//
//  ChartV.m
//  UHealth
//
//  Created by gjtxz on 15/1/10.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "ChartV.h"
#import "CorePlot-CocoaTouch.h"
#import "BodyTemperatureObj.h"
#import "NSString+BloodSugar.h"

@interface ChartV ()<CPTPlotDataSource,CPTAxisDelegate>
{
//    CPTXYGraph              *_graph;
//    NSMutableDictionary     *_dataDic;
}

@property (nonatomic, strong)NSArray        *dataArray;
@property (nonatomic, strong)CPTXYGraph     *graph;
@property (nonatomic, strong)CPTScatterPlot *scatterPlot;

@end

@implementation ChartV

//- (id)initWithFrame:(CGRect)frame
//{
//    self = [super initWithFrame:frame];
//    if (self) {
//        [self DrawViewWithFrame:frame];
//    }
//    return self;
//}

- (instancetype)initWithFrame:(CGRect)frame dataArray:(NSArray *)dataArray
{
    if (self = [super initWithFrame:frame]) {
        self.dataArray = dataArray;
        [self DrawViewWithFrame:frame];
    }
    return self;
}

-(void)DrawViewWithFrame:(CGRect)frame
{
//    _dataDic = [[NSMutableDictionary alloc] init];
    
    CPTGraphHostingView *hostView = [[CPTGraphHostingView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    [self addSubview:hostView];//把 CPTGraphHostingView 加到你自己的 View 中
    hostView.backgroundColor = [UIColor clearColor];
    
    _graph = [[CPTXYGraph alloc] initWithFrame:hostView.frame];
    hostView.hostedGraph = _graph;
//    [_graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];//主题
//    _graph.title = @"dddd";
    
   //线条的样式
    CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
    lineStyle.lineColor = [CPTColor grayColor];
    
    
    //设置图表的padding
    _graph.plotAreaFrame.masksToBorder = NO;
    _graph.paddingBottom = 20.0;
    _graph.paddingLeft   = 50.0;
    _graph.paddingRight  = 15.0;
    _graph.paddingTop    = 0.0;
//    _graph.plotAreaFrame.paddingBottom  = 1.0;
//    _graph.plotAreaFrame.paddingTop     = 20.0;
//    _graph.plotAreaFrame.paddingLeft    = 2.0;
//    _graph.plotAreaFrame.paddingRight   = 2.0;
    
    //边界线条
    lineStyle.lineWidth = 2.0;
    _graph.plotAreaFrame.plotArea.borderLineStyle = lineStyle;
    
    //xy轴限制
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)_graph.defaultPlotSpace;
    plotSpace.allowsUserInteraction = YES;//允许滑动
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(15)];
    plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(1000)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(12)];
    plotSpace.globalYRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(30) length:CPTDecimalFromInt(42)];
   
    // 创建坐标轴
    CPTXYAxisSet *axisSet  = (CPTXYAxisSet *)_graph.axisSet ;
    CPTXYAxis *xAxis       = axisSet.xAxis;
    xAxis.majorIntervalLength       = CPTDecimalFromInt(3);// 大刻度线间距
    xAxis.minorTicksPerInterval     = 0;//大间隔有几个小间隔
    xAxis.majorTickLineStyle        = lineStyle;
    xAxis.identifier                = @"x";
    xAxis.delegate = self;
    xAxis.orthogonalCoordinateDecimal = CPTDecimalFromInt(30);// 坐标原点
    xAxis.title                       = kLocal(@"chart_x");
    
    CPTXYAxis *yAxis                = axisSet.yAxis;
    yAxis.majorIntervalLength       = CPTDecimalFromFloat(2.0);
    yAxis.minorTicksPerInterval     = 0;
    yAxis.identifier                = @"y";
    yAxis.delegate = self;
    yAxis.orthogonalCoordinateDecimal = CPTDecimalFromInt(0);
    yAxis.title                       = kLocal(@"chart_y");
//    NSArray * exclusionRanges = [NSArray arrayWithObjects:
//                                 [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(2.7)],
//                                 [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(2.8) length:CPTDecimalFromFloat(4.0)],
//                                 nil];
//    yAxis.labelExclusionRanges = exclusionRanges;// 不显示数字的主刻度
    
    //坐标轴线
    lineStyle.lineWidth  = 2.0;
    xAxis.axisLineStyle      = lineStyle;
    yAxis.axisLineStyle      = lineStyle;
    
    //折线
    lineStyle.lineWidth = 2.0;
//    [UIColor colorWithRed:9/255.0f green:145/255.0f blue:253/255.0f alpha:1.0]
//    [UIColor colorWithRed:36.0/255.0 green:176.0/255.0 blue:237.0/255.0 alpha:1.f]
    
    lineStyle.lineColor = [CPTColor colorWithComponentRed:36.0/255.0 green:176.0/255.0 blue:237.0/255.0 alpha:1.f];
    CPTScatterPlot *scatterPlot = [[CPTScatterPlot alloc] init];
    scatterPlot.dataLineStyle   = lineStyle;
//    scatterPlot.areaBaseValue   = CPTDecimalFromFloat(11.1);
//    scatterPlot.areaFill        = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:237.0/255.0 green:206.0/255.0 blue:219.0/255.0 alpha:0.7f]];//设置下面背景填充
//    scatterPlot.areaBaseValue2   = CPTDecimalFromFloat(20);
//    scatterPlot.areaFill2        = [CPTFill fillWithColor:[CPTColor  redColor]];//设置下面背景填充
    scatterPlot.dataSource      = self;
    scatterPlot.interpolation   = CPTScatterPlotInterpolationCurved;
    [_graph addPlot:scatterPlot];
    
    CPTMutableLineStyle *symbolLineStyle = [CPTMutableLineStyle lineStyle];
    symbolLineStyle.lineColor   = [CPTColor colorWithComponentRed:234/255.0f green:99/255.0f blue:106/255.0f alpha:1];
    CPTPlotSymbol *plotSymbol   = [CPTPlotSymbol ellipsePlotSymbol];
    plotSymbol.fill             = [CPTFill fillWithColor:[CPTColor redColor]];
    plotSymbol.lineStyle        = symbolLineStyle;
    plotSymbol.size             = CGSizeMake(2.0, 2.0);
    scatterPlot.plotSymbol      = plotSymbol;//小圆点
    
    lineStyle.lineWidth = 0.5f;
    lineStyle.lineColor = [CPTColor grayColor];
    lineStyle.dashPattern = [NSArray arrayWithObjects:[NSNumber numberWithFloat:5.0f],[NSNumber numberWithFloat:5.0f],nil];
 
    //网格线
    
//    xAxis.majorGridLineStyle = lineStyle;
//    xAxis.minorGridLineStyle = lineStyle;
    yAxis.majorGridLineStyle = lineStyle;
//    yAxis.minorGridLineStyle = lineStyle;
}

//- (void)refreshViewWithDataArray:(NSArray *)dataArray
//{
//    self.dataArray = dataArray;
//    [_graph reloadData];
//}

- (void)refreshViewWithDataArray:(NSArray *)dataArray
{
    self.dataArray = dataArray;
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet ;
    CPTXYAxis *xAxis = axisSet.xAxis;
    NSMutableArray *labelArray = [NSMutableArray array];
    NSMutableArray *dateArray  = [NSMutableArray array];
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        //        BloodSugarDataObj *obj = self.dataArray[i];
        BodyTemperatureObj *obj = self.dataArray[i];
        NSString *dateStr = [[NSString stringFromDate:obj.measureDate] substringWithRange:NSMakeRange(11, 8)];
        [dateArray addObject:dateStr];
    }
    float labelLocation = 1;
    for (NSString *dateStr in dateArray) {
        CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
        textStyle.fontSize = 15;
        textStyle.color = [CPTColor colorWithComponentRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1.0];
        CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:dateStr textStyle:textStyle];
        label.tickLocation = [[NSNumber numberWithFloat:labelLocation] decimalValue];
        label.offset = xAxis.labelOffset + xAxis.majorTickLength;
        label.rotation = M_PI/4.0;
        [labelArray addObject:label];
        labelLocation += 1.5;
    }
    xAxis.axisLabels = [NSSet setWithArray:labelArray];
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(labelLocation - 15.0)
                                                    length:CPTDecimalFromDouble(15.0)];
    //    int xmax = self.dataArray.count;
    plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat (0.0f) length:CPTDecimalFromFloat(labelLocation+3)];
    
    [_graph reloadData];
}


//-(void)refreshViewWithDataDic:(NSDictionary *)dict
//{
//    _dataDic = [dict mutableCopy];
//    [_graph reloadData];
//}

#pragma mark - CPTPlotDataSource
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
//    NSArray *arr = [_dataDic objectForKey:kGraphData];
//    return arr.count;
    return self.dataArray.count;
}

//询问一个个数据值，在 CPTPlotDataSource 中声明的
- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx {
    
    if(fieldEnum == CPTScatterPlotFieldY){    //询问 Y 值时
//        NSArray *arr = [_dataDic objectForKey:kGraphData];
//        return [arr objectAtIndex:idx];
        BodyTemperatureObj *obj = self.dataArray[idx];
        return [NSDecimalNumber numberWithFloat:obj.bodyTemperatureValue];
    }else{                                    //询问 X 值时
//        float offSet = [[_dataDic objectForKey:kOffSet] floatValue];
//        return [NSNumber numberWithFloat:(idx+offSet)/20.0f];
        return [NSDecimalNumber numberWithFloat:1.5*idx + 1];    // X轴上的数值表示
    }
}

#pragma mark -- CPTAxisDelegate
- (BOOL)axis:(CPTAxis *)axis shouldUpdateAxisLabelsAtLocations:(NSSet *)locations
{
    static CPTTextStyle * positiveStyle = nil;
    NSFormatter * formatter   = axis.labelFormatter;
    CGFloat labelOffset             = axis.labelOffset;
    NSMutableSet * newLabels        = [NSMutableSet set];
    for (NSDecimalNumber * tickLocation in locations) {
        CPTTextStyle *theLabelTextStyle;
        if (!positiveStyle) {
            CPTMutableTextStyle * newStyle = [axis.labelTextStyle mutableCopy];
            newStyle.color = [CPTColor colorWithComponentRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1.0];
            positiveStyle  = newStyle;
        }
        theLabelTextStyle = positiveStyle;
        NSString * labelString      = [formatter stringForObjectValue:tickLocation];
        CPTTextLayer * newLabelLayer= [[CPTTextLayer alloc] initWithText:labelString style:theLabelTextStyle];
        
        CPTAxisLabel * newLabel     = [[CPTAxisLabel alloc] initWithContentLayer:newLabelLayer];
        newLabel.tickLocation       = tickLocation.decimalValue;
        newLabel.offset             = labelOffset;
        
        [newLabels addObject:newLabel];
    }
    axis.axisLabels = newLabels;
    
    return YES;
    
}
@end
